package org.xxpay.agent.user.ctrl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.xxpay.agent.common.ctrl.BaseController;
import org.xxpay.core.common.constant.Constant;
import org.xxpay.core.common.constant.MchConstant;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.constant.RetEnum;
import org.xxpay.core.common.domain.XxPayPageRes;
import org.xxpay.core.common.domain.XxPayResponse;
import org.xxpay.core.common.util.AmountUtil;
import org.xxpay.core.common.util.DateUtil;
import org.xxpay.core.entity.AgentAccount;
import org.xxpay.core.entity.AgentAccountHistory;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.core.entity.PayProduct;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author: dingzhiwei
 * @date: 17/12/6
 * @description:
 */
@RestController
@RequestMapping(Constant.AGENT_CONTROLLER_ROOT_PATH + "/account")
@PreAuthorize("hasRole('"+ MchConstant.AGENT_ROLE_NORMAL+"')")
public class AccountController extends BaseController {
    
    /**
     * 查询账户信息
     * @return
     */
    @RequestMapping("/get")
    @ResponseBody
    public ResponseEntity<?> get() {
        AgentAccount agentAccount = commonService.agentAccountService.findByAgentId(getUser().getId());
        JSONObject object = (JSONObject) JSON.toJSON(agentAccount);
        object.put("availableBalance", agentAccount.getAvailableBalance());       // 可用余额
        object.put("availableSettAmount", agentAccount.getAvailableSettAmount()); // 可结算金额
        return ResponseEntity.ok(XxPayResponse.buildSuccess(object));
    }

    /**
     * 查询资金流水列表
     * @return
     */
    @RequestMapping("/history_list")
    @ResponseBody
    public ResponseEntity<?> historyList(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        AgentAccountHistory agentAccountHistory = getObject(param, AgentAccountHistory.class);
        if(agentAccountHistory == null) agentAccountHistory = new AgentAccountHistory();
        agentAccountHistory.setAgentId(getUser().getId());
        int count = commonService.agentAccountHistoryService.count(getUser().getId(), agentAccountHistory, getQueryObj(param));
        if(count == 0) return ResponseEntity.ok(XxPayPageRes.buildSuccess());
        List<AgentAccountHistory> agentAccountHistoryList = commonService.agentAccountHistoryService
                .select(getUser().getId(), (getPageIndex(param) - 1) * getPageSize(param), getPageSize(param), agentAccountHistory, getQueryObj(param));
        return ResponseEntity.ok(XxPayPageRes.buildSuccess(agentAccountHistoryList, count));
    }

    /**
     * 查询资金流水
     * @return
     */
    @RequestMapping("/history_get")
    @ResponseBody
    public ResponseEntity<?> historyGet(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Long id = getLongRequired(param, "id");
        AgentAccountHistory agentAccountHistory = commonService.agentAccountHistoryService
                .findByAgentIdAndId(getUser().getId(), id);
        return ResponseEntity.ok(XxPayResponse.buildSuccess(agentAccountHistory));
    }


    @RequestMapping("/exportExcel")
    @ResponseBody
    public String exportExcel(HttpServletRequest request) throws Exception {

        JSONObject param = getJsonParam(request);
        AgentAccountHistory agentAccountHistory = getObject(param, AgentAccountHistory.class);
        if(agentAccountHistory == null) agentAccountHistory = new AgentAccountHistory();
        agentAccountHistory.setAgentId(getUser().getId());
        int count = commonService.agentAccountHistoryService.count(getUser().getId(), agentAccountHistory, getQueryObj(param));

        if(count > MchConstant.MAX_EXPORT_ROW) return RetEnum.RET_SERVICE_OUT_OF_RANGE_MAX_EXPORT_ROW.getMessage();

        List<AgentAccountHistory> agentAccountHistoryList = commonService.agentAccountHistoryService
                .select(getUser().getId(), 0, MchConstant.MAX_EXPORT_ROW, agentAccountHistory, getQueryObj(param));

        List<List> excelData = new ArrayList<>();
        List header = Arrays.asList(new String[]{"记录ID", "变更前余额(元)", "变更金额(元)", "变更后余额(元)", "业务类型", "业务类目", "业务订单", "时间"});
        excelData.add(header);
        for(AgentAccountHistory record : agentAccountHistoryList){
            List rowData = new ArrayList<>();
            rowData.add(record.getId());
            rowData.add(AmountUtil.convertCent2Dollar(record.getBalance()+""));

            String prefix = record.getFundDirection() == MchConstant.FUND_DIRECTION_ADD ? "+" : "-";
            rowData.add(prefix + AmountUtil.convertCent2Dollar(record.getAmount()+""));

            rowData.add(AmountUtil.convertCent2Dollar(record.getAfterBalance()+""));
            rowData.add(MchConstant.convertBizType(record.getBizType(), MchConstant.SYSTYPE_AGENT));
            rowData.add(MchConstant.convertBizItem(record.getBizItem()));
            rowData.add(record.getOrderId());
            rowData.add(DateUtil.date2Str(record.getCreateTime()));
            excelData.add(rowData);
        }

        super.writeExcelStream("资金流水", excelData);
        return null;
    }

    /**
     * 查询资金流水统计数据
     * @return
     */
    @RequestMapping("/count")
    @ResponseBody
    public ResponseEntity<?> count(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        String orderId = getString(param, "orderId");
        Byte fundDirection = getByte(param, "fundDirection");
        Byte bizType = getByte(param, "bizType");
        String bizItem = getString(param, "bizItem");
        Long agentId = getUser().getId();
        // 订单起止时间
        String createTimeStartStr = getString(param, "createTimeStart");
        String createTimeEndStr = getString(param, "createTimeEnd");

        JSONObject object = commonService.agentAccountHistoryService.count4Agent(agentId, orderId, fundDirection,
                bizType, bizItem, createTimeStartStr, createTimeEndStr);

        return ResponseEntity.ok(XxPayResponse.buildSuccess(object));
    }

}
